package test.mapper;

/**
 *
 */
import test.util.DBUtil;
import test.vo.Article;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class AticleMapper {
    public int insertArticle(Article aticle){

        try (
            Connection connection = DBUtil.getConnection();
        ){
            String sql = "INSERT INTO article(title,content) "+
                    "VALUES(?,?)";
            PreparedStatement ps = connection.prepareStatement(sql);
            ps.setString(1, aticle.getTitle());
            ps.setString(2, aticle.getContent());
            return ps.executeUpdate();

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }
    public int deleteArticle(int id){

        try (
            Connection connection = DBUtil.getConnection();
        ){
            String sql = "DELETE FROM article " +
                    "WHERE id = ?";
            PreparedStatement ps = connection.prepareStatement(sql);
            ps.setInt(1, id);
            return ps.executeUpdate();

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }
    public Article findById(int id){

        try (
            Connection connection = DBUtil.getConnection();
        ){
            String sql = "SELECT title,content " +
                    "FROM article " +
                    "WHERE id = ?";
            PreparedStatement ps = connection.prepareStatement(sql);
            ps.setInt(1, id);
            ResultSet rs = ps.executeQuery();
            if (rs.next()){
                String title = rs.getString("title");
                String content = rs.getString("content");
                Article article = new Article();
                article.setTitle(title);
                article.setContent(content);
                return article;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
    public List<Article> findAll(){
        try (
            Connection connection = DBUtil.getConnection();
        ){
            Statement statement = connection.createStatement();
            String sql = "SELECT title,content FROM article";
            List<Article> list = new ArrayList<>();
            ResultSet resultSet = statement.executeQuery(sql);
            while (resultSet.next()){
                String title = resultSet.getString("title");
                String content = resultSet.getString("content");
                Article article = new Article();
                article.setTitle(title);
                article.setContent(content);
                list.add(article);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}
